package com.wcq.dessert.core;

import com.wcq.dessert.support.SysException;

import java.lang.reflect.Constructor;

public abstract class Service {
    protected String name;
    protected Port port;

    private RPCImplBase methodFunctionProxy;

    public Service(String serviceName, Port port){
        this.name = serviceName;
        this.port = port;
    }

    public void pulse(){

    }

    /**
     * 获取RPC函数调用
     * @param funcKey
     * @return
     */
    public Object getMethodFunction(int funcKey) {
        try {
            // 获取对应的代理类
            if (methodFunctionProxy == null) {
                Class<?> cls = Class.forName(getClass().getName() + "Impl");
                Constructor<?> c = cls.getDeclaredConstructor();
                c.setAccessible(true);
                methodFunctionProxy = (RPCImplBase)c.newInstance();
            }

            // 通过代理类 获取函数引用
            return methodFunctionProxy.getMethodFunction(this, funcKey);
        } catch (Exception e) {
            throw new SysException(e);
        }
    }

    public void returns(Call call) {
        call.type = 2;
        port.addCall(call);
    }
}
